package cn.wolfcode.web.controller;

import cn.wolfcode.domain.Department;
import cn.wolfcode.domain.Employee;
import cn.wolfcode.domain.JsonResult;
import cn.wolfcode.domain.Role;
import cn.wolfcode.qo.EmployeeQueryObject;
import cn.wolfcode.service.IDepartmentService;
import cn.wolfcode.service.IEmpRoleService;
import cn.wolfcode.service.IEmployeeService;
import cn.wolfcode.service.IRoleService;
import cn.wolfcode.util.RequiredPermission;
import com.github.pagehelper.PageInfo;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired
    private IEmployeeService employeeService;
    @Autowired
    private IDepartmentService departmentService;
    @Autowired
    private IRoleService roleService;
    @Autowired
    private IEmpRoleService empRoleService;

    @RequiredPermission(name="员工列表",expression="employee:list")
    @RequestMapping("/list")
    public String list(Model model, @ModelAttribute("qo") EmployeeQueryObject qo){
        PageInfo<Employee> pageInfo = employeeService.query(qo);
        List<Department> departments = departmentService.listAll();
        model.addAttribute("departments",departments);
        //key-value
        model.addAttribute("pageInfo",pageInfo);
        return "/employee/list";
    }

    @RequiredPermission(name="员工删除",expression="employee:delete")
    @RequestMapping("/delete")
    public String delete(Long id){
        //System.out.println(id);
        employeeService.delete(id);
        return "redirect:/employee/list";
    }
    @RequiredPermission(name="员工新增/编辑",expression="employee:saveOrUpdate")
    @RequestMapping("/input")
    public String input(Long id,Model model){
        List<Department> departments = departmentService.listAll();
        model.addAttribute("departments",departments);
        List<Role> roles = roleService.listRoles();
        model.addAttribute("roles",roles);
        if(id!=null){
            //去修改
            List<Role> rolesForId = employeeService.queryRoles(id);
            model.addAttribute("rolesForId",rolesForId);
            Employee employee = employeeService.get(id);
            model.addAttribute("employee",employee);
        }
        return "/employee/input";
    }

    @RequiredPermission(name="员工新增/编辑",expression="employee:saveOrUpdate")
    @RequestMapping("/saveOrUpdate")
    @ResponseBody
    public JsonResult saveOrUpdate(Employee employee, Long[] ids){
        //System.out.println(employee);
        if(employee.getId()==null){
            //System.out.println(employee);
            //执行增加操作
            employeeService.insert(employee);
        }else{
            //修改之前删除该员工关联角色的关系
            empRoleService.deleteRelation(employee.getId());
            //执行修改操作
            employeeService.update(employee);
        }
        if(ids!=null){
            for (Long id : ids) {
                empRoleService.insertRelation(employee.getId(),id);
            }
        }
//        //如果管理员被选中,添加所有角色到该员工
//        if(employee.getAdmin()){
//            List<Role> roles = roleService.listRoles();
//            for (Role role : roles) {
//                empRoleService.insertRelation(employee.getId(),role.getId());
//            }
//        }
        return new JsonResult();
    }

    @RequestMapping("/checkName")
    @ResponseBody
    public Map checkName(String username){
        HashMap<String, Boolean> map = new HashMap<>();
        Employee employee = employeeService.selectByUsername(username);
        map.put("valid",employee==null);//验证不通过返回false,验证通过返回true
        return map;
    }


    @RequestMapping("/exportXls")
    @ResponseBody
    public void exportXls(HttpServletResponse response) throws Exception {
        //文件下载的响应头（让浏览器访问资源的的时候以下载的方式打开）
        response.setHeader("Content-Disposition","attachment;filename=employee1.xls");
        //创建excel文件
        Workbook wb = employeeService.exportXls();
        //把excel的数据输出给浏览器
        wb.write(response.getOutputStream());
    }

    @RequestMapping("/importXls")
    //@ResponseBody
    public String importXls(MultipartFile file) throws Exception {
        employeeService.importXls(file);
        return "redirect:/employee/list";
    }


    @RequestMapping("/resetPassword")
    public String resetPassword(Long id, HttpSession session){
        Employee employee = employeeService.get(id);
        employee.setPassword("8888");
        employeeService.update(employee);
        //删session
        session.invalidate();
        return "redirect:/login.html";
    }


    @RequiredPermission(name="员工状态禁用/恢复",expression="employee:changeStatus")
    @RequestMapping("/changeStatus")
    public String changeStatus(boolean status,Long id){

        employeeService.changeStatus(!status,id);
        return "redirect:/employee/list";
    }

}
